<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="产品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入产品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品编号" prop="productNo">
        <el-input
          v-model="queryParams.productNo"
          placeholder="请输入产品编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small"
                   @change="handleQuery"
        >
          <el-option label="上架" value="0"/>
          <el-option label="下架" value="1"/>
        </el-select>
      </el-form-item>


      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['module:product:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['module:product:delete']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" border :data="productList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="产品名称" align="center"  prop="productName" />
      <el-table-column label="产品编号" width="200" align="center" prop="productNo" />
      <el-table-column label="产品分类" align="center" prop="productType" />
      <el-table-column label="型号" align="center" prop="modelCount">
        <template slot-scope="scope" >
          <span style="color: #00afff" v-if="scope.row.modelCount >0 " @click="showModel(scope.row)">{{ scope.row.modelCount }}种型号</span>
        </template>
      </el-table-column>
      <el-table-column label="单位" align="center" prop="unit" />
      <el-table-column label="库存" align="center" prop="quantity" />
      <el-table-column label="可见部门" width="200" align="center" prop="visibleDeptName" />
      <el-table-column label="可见人" align="center" prop="visibleUserName" />
      <el-table-column label="创建者" align="center" prop="createBy" />
<!--      <el-table-column label="产品图片" align="center" prop="image" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.image" :width="50" :height="50"/>
        </template>
      </el-table-column>-->
      <el-table-column label="产品介绍"  align="center" prop="introduce" width="200" />
<!--      <el-table-column label="附件" align="center" prop="enclosure" />-->
      <el-table-column label="仓库名称" align="center" prop="warehouseName" />
      <el-table-column label="状态" align="center" prop="status" >
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status == '0'" type="success">上架</el-tag>
          <el-tag v-if="scope.row.status == '1'" type="info">下架</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="上架时间" align="center" prop="putOnTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.putOnTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="下架时间" align="center" prop="putDownTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.putDownTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['module:product:update']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['module:product:delete']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="updateStatus(scope.row)"
            v-if="scope.row.status == '0'"
            v-hasPermi="['module:product:update']"
          >下架</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="updateStatus(scope.row)"
            v-if="scope.row.status == '1'"
            v-hasPermi="['module:product:update']"
          >上架</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改产品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="产品名称" prop="productName"  >
          <el-input v-model="form.productName" placeholder="请输入产品名称" />
        </el-form-item>
        <el-form-item label="产品编号" prop="productNo">
          <el-input v-model="form.productNo"  readonly placeholder="请输入产品编号" />
        </el-form-item>
<!--        <el-form-item label="型号" prop="model">
          <el-input v-model="form.model" type="textarea" placeholder="请输入内容" />
        </el-form-item>-->
        <el-form-item label="型号" prop="model">
        <div >
          <el-form  label-width="120px"  >
            <el-button type="primary" size="mini" @click="addModel" style="margin-bottom: 10px">新增</el-button>
            <div v-for="(item,index) in  models" :key="index" style="margin-top: 10px">
              <el-form-item :prop="'model.' + index"  label-width="1px">
                <div style="display:flex;">
                  型号：<el-input v-model="item.model" class="whiteBankCard" placeholder="请输入型号" style="width: 150px;margin-right: 10px" />
                  价格：<el-input v-model="item.price" placeholder="请输入价格" class="whiteBankCard" style="width: 120px;margin-right: 10px"/>
                  <el-button type="danger" size="mini" @click="removeModel(index)" style="height: 30px" v-if="index>0">删除</el-button>
                </div>
              </el-form-item>
            </div>
          </el-form>
        </div>
        </el-form-item>

        <el-form-item label="单位" prop="unit">
          <el-select v-model="form.unit" placeholder="请输入单位">
            <el-option
              v-for="item in unitOptions"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产品分类" prop="productType">
          <el-select v-model="form.productType" placeholder="产品分类">
            <el-option
              v-for="item in productTypeOptions"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
<!--        <el-form-item label="可见部门id" prop="visibleDept">
          <el-input v-model="form.visibleDept" type="textarea" placeholder="请输入内容" />
        </el-form-item>-->
        <el-form-item label="可见部门" prop="visibleDeptName">
          <el-input v-model="form.visibleDeptName" readonly placeholder="">
            <template slot="append">
              <el-button type="primary" style="width: 120px" @click="openImportDept">
                选择部门
              </el-button>
            </template>
          </el-input>
        </el-form-item>
<!--        <el-form-item label="可见人id" prop="visibleUser">
          <el-input v-model="form.visibleUser" type="textarea" placeholder="请输入内容" />
        </el-form-item>-->
        <el-form-item label="可见人" prop="visibleUserName">
          <el-input v-model="form.visibleUserName" readonly placeholder="">
            <template slot="append">
              <el-button type="primary" style="width: 120px" @click="openImportUser">
                选择可见人
              </el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="产品介绍" prop="introduce">
          <el-input v-model="form.introduce" type="textarea"  size="small" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="产品图片">
          <image-upload v-model="form.image"/>
        </el-form-item>
        <el-form-item label="附件" prop="enclosure">
          <image-upload v-model="form.enclosure"/>
        </el-form-item>
<!--        <el-form-item label="仓库id" prop="warehouseId">
          <el-input v-model="form.warehouseId" type="textarea" placeholder="请输入内容" />
        </el-form-item>-->
        <el-form-item label="仓库名称" prop="warehouseName">
          <el-input v-model="form.warehouseName" readonly placeholder="">
            <template slot="append">
              <el-button type="primary" style="width: 120px" @click="openImportWarehouse">
                选择仓库
              </el-button>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
<!--产品型号弹框操作-->
    <el-dialog :title="modelTitle" :visible.sync="modelOpen" width="50%" >
<!--      <table>-->
<!--        <tr>-->
<!--          <td style="width:150px;font-weight:bold">型号</td>-->
<!--          <td style="font-weight:bold">数量</td>-->
<!--        </tr>-->
<!--        <template v-for="(item1,index) in productModelList">-->
<!--          <tr>-->
<!--            <td style="width:150px">{{ item1.model }}</td>-->
<!--            <td style="color: #f4516c">{{ item1.quantity }}</td>-->
<!--          </tr>-->
<!--        </template>-->
<!--      </table>-->
      <el-table
        :data="productModelList"
        stripe
        style="width: 100%">
        <el-table-column
          prop="productId"
          label="产品ID"
          width="180">
        </el-table-column>
        <el-table-column
          prop="productName"
          label="产品名称"
          width="180">
        </el-table-column>
        <el-table-column
          prop="model"
          label="产品型号">
        </el-table-column>
        <el-table-column
          prop="price"
          label="产品价格">
        </el-table-column>
      </el-table>
    </el-dialog>

    <import-user ref="import" @showUser="showUser"></import-user>
    <import-dept ref="importDept" @showDept="showDept"></import-dept>
    <import-warehouse ref="importWarehouse" @showWarehouse="showWarehouse"></import-warehouse>
  </div>
</template>

<script>
import { listProduct, getProduct, delProduct, addProduct, updateProduct } from "@/api/module/product";
import {getDicts} from "@/api/system/dict/data";
import importUser from "@/views/module/customer/user";
import importDept from "@/views/module/warehouse/dept";
import importWarehouse from "./warehouse";

export default {
  name: "Product",
  components: { importUser, importDept,importWarehouse},
  data() {
    return {
      // 弹出层标题
      modelTitle: "",
      // 是否显示弹出层
      modelOpen: false,
      productModelList:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 产品表格数据
      productList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productName: null,
        productNo: null,
        productType: null,
        model: null,
        unit: null,
        visibleDept: null,
        visibleDeptName: null,
        visibleUser: null,
        visibleUserName: null,
        createId: null,
        status: null,
        image: null,
        introduce: null,
        enclosure: null,
        warehouseId: null,
        warehouseName: null,
        putDownTime: null,
        putOnTime: null
      },
      // 表单参数
      form: {

      },
      // 表单校验
      rules: {
        productName:[{required:true,message:'请输入产品名称',trigger:'blur'}],
        productNo:[{required:true,message:'请输入编号',trigger:'blur'}],

      },
      productTypeOptions: [], // 分类
      unitOptions: [], // 单位
      models: [{
        model: ''
      }]
    };
  },
  created() {
    this.getList();
    this.getProductTypeOptions();
    this.getUnitOptions();
    this.getProductNo();
  },
  methods: {
    /** 查询产品列表 */
    getList() {
      this.loading = true;
      listProduct(this.queryParams).then(response => {
        this.productList = response.rows;
        // 产品类型判断
        let arr = this.productList;
        arr.forEach(item => {
          item.productType = this.getValue(this.productTypeOptions, item.productType);
          item.unit = this.getValue(this.unitOptions, item.unit)
        });
        this.productList = arr;
        this.total = response.total;
        this.loading = false;
      });
    }
    ,
    getValue(arr, item) {
      for (let i = 0; i < arr.length; i++) {
        if (item === arr[i].dictValue) {
          return arr[i].dictLabel
        }
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        productName: null,
        productNo: null,
        productType: null,
        model: null,
        unit: null,
        visibleDept: null,
        visibleDeptName: null,
        visibleUser: null,
        visibleUserName: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        delFlag: null,
        createId: null,
        remark: null,
        status: "0",
        image: null,
        introduce: null,
        enclosure: null,
        warehouseId: null,
        warehouseName: null,
        putDownTime: null,
        putOnTime: null
      };
      this.resetForm("form");
      this.models= [{
        model: '',
        id:''
      }]
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.form.productNo=this.getProductNo();
      this.title = "添加产品";
    },
    getProductNo (){
      var date = new Date();
      var year = date.getFullYear();        //年 ,从 Date 对象以四位数字返回年份
      var month = date.getMonth() + 1;      //月 ,从 Date 对象返回月份 (0 ~ 11) ,date.getMonth()比实际月份少 1 个月
      var day = date.getDate();             //日 ,从 Date 对象返回一个月中的某一天 (1 ~ 31)
      var hours = date.getHours();          //小时 ,返回 Date 对象的小时 (0 ~ 23)
      var minutes = date.getMinutes();      //分钟 ,返回 Date 对象的分钟 (0 ~ 59)
      var seconds = date.getSeconds();      //秒 ,返回 Date 对象的秒数 (0 ~ 59)
      //修改月份格式
      if (month >= 1 && month <= 9) {
        month = "0" + month;
      }
      //修改日期格式
      if (day >= 0 && day <= 9) {
        day = "0" + day;
      }
      //修改小时格式
      if (hours >= 0 && hours <= 9) {
        hours = "0" + hours;
      }
      //修改分钟格式
      if (minutes >= 0 && minutes <= 9) {
        minutes = "0" + minutes;
      }
      //修改秒格式
      if (seconds >= 0 && seconds <= 9) {
        seconds = "0" + seconds;
      }
      let round = Math.floor(Math.random() * (99 - 10)) + 10;
      var currentFormatDate = `${year}${month}${day}${hours}${minutes}${seconds}${round}`;
      return currentFormatDate;
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getProduct(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改产品";
        this.models=this.form.models;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateProduct(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.models=this.models;
            addProduct(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除产品编号为"' + ids + '"的数据项？').then(function() {
        return delProduct(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('module/product/export', {
        ...this.queryParams
      }, `product_${new Date().getTime()}.xlsx`)
    },
    // 获取类型
    getProductTypeOptions() {
      getDicts('biz_product_type').then(response => {
        this.productTypeOptions = response.data
      })
    },
    // 获取单位
    getUnitOptions() {
      getDicts('biz_unit').then(response => {
        this.unitOptions = response.data
      })
    },
    /** 打开部门弹窗 */
    openImportDept() {
      this.$refs.importDept.show();
    },
    /** 打开负责人弹窗 */
    openImportUser() {
      this.$refs.import.show(1,1);
    },
    /** 打开仓库弹窗 */
    openImportWarehouse() {
      this.$refs.importWarehouse.show(1,1);
    },
    showUser(data){
      //负责人
      this.form.visibleUser=data.userId;
      this.form.visibleUserName=data.userName;
    },
    showDept(data){
      //部门
      this.form.visibleDept=data.deptId;
      this.form.visibleDeptName=data.deptName;
    },
    showWarehouse(data){
      //仓库
      this.form.warehouseId=data.id;
      this.form.warehouseName=data.name;
    },
    /** 删除按钮操作 */
    updateStatus(row) {
      this.reset();
      let  id = row.id;
      let  status= row.status;
      if(status == "0"){
        status = "1";
        this.form.putDownTime = new Date();
      }else{
        status = "0";
        this.form.putOnTime = new Date();
      }
      this.form.id=id;
      this.form.status=status;

      updateProduct(this.form).then(response => {
        this.$modal.msgSuccess("操作成功");
        this.getList();
      });
    },
    //新增产品型号
    addModel() {
      this.models.push({
        model: '',
        id:''
      })
    },
    removeModel(index) {
      this.models.splice(index, 1)
    },
    //产品型号信息
    showModel(row){
      this.productModelList=row.models;
      this.modelOpen = true;
      this.modelTitle = "型号信息";
      console.log(this.productModelList)
    }
  }
};
</script>
